'use strict';

const moment = require('moment');
const recordDb = require('../models/record');
const request = require('request');
const config = require('../config/config');

const log =  require('../lib/log4js')();

async function getRecord(req, res){

  try {

    var body = req.query;

    var codeData = await getCodeData(body.code);

    var ret = await recordDb.create({
      orderNo: body.orderNo,
      openId: body.openId,
      source: body.source,
      env: body.env,
      accode: body.accode,
      name: body.name,
      nickName: body.nickName,
      mobile: body.mobile,
      status: 1,
      code: body.code,
      selflon: body.lon,
      selflat: body.lat,
      codelon: codeData.lon,
      codelat: codeData.lat,
      img: body.img,
      adminOpenId: codeData.openId,
      createTime: createTime
    });

    res.redirect(config.wxLink);

  }catch(error){
    log.error('api res:' + req.route.path + ' res error: ' + error.toString());
    res.redirect(config.wxLink);
  };

};

function getCodeData(code){

  return new Promise(function(resolve, reject){

    var url = config.codeServerUrl + code;
  
    request(url, function(error, response, body) {
      if (!error && response.statusCode == 200 ) {
        resolve(body);
      }else{
        reject({ error: error, statusCode: response.statusCode });	
      };
    });

  });

};

module.exports = {
  getRecord: getRecord
}